package com.weight;


import java.io.File;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.text.Html;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;

import com.weight.data.DataBaseHelper;
import com.weight.data.model.Registry;
import com.weight.util.Constants;
import com.weight.util.Utilities;

public class LogRegistry extends ListActivity {
	 public static final int PICK_CONTACT = 0;

    CursorAdapter cursorAd;
	 
	private boolean weightKilograms;
	
	private Button send_mail;
	
    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);       
        setContentView(R.layout.registry);
        
    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);      
        
		String selectedmeasure = pref.getString("listofmeasures", null);
		
		send_mail = (Button) findViewById(R.id.send_mail);
		
		weightKilograms = "Kilograms".equals(selectedmeasure);
        
        cursorAd = new CursorAdapter(this,DataBaseHelper.getInstance().getCursor(weightKilograms)) {
        
            private LayoutInflater _mInflater = LayoutInflater.from(LogRegistry.this);
            
            @Override
            public View newView( Context context, Cursor cursor, ViewGroup parent ) {
                View v = _mInflater.inflate(R.layout.registry_item, parent, false);
                return v;
            }
            
            @Override
            public void bindView( View view, Context context,final Cursor cursor ) {
                final EditText date = (EditText) view.findViewById(R.id.dateView);
                final EditText weight =(EditText) view.findViewById(R.id.weightView);                
                
                final int _id = cursor.getInt(cursor.getColumnIndex("_id"));
                date.setText(cursor.getString(cursor.getColumnIndex(Constants.WEIGHT_TABLE_DATE_COLUMN)));
                weight.setText(cursor.getString(cursor.getColumnIndex(Constants.WEIGHT_TABLE_WEIGHT_COLUMN)));
                
                View.OnKeyListener keyListener = new View.OnKeyListener() {
					
					@Override
					public boolean onKey(View arg0, int keyCode, KeyEvent arg2) {
						if(keyCode==KeyEvent.KEYCODE_ENTER) {
						Registry registry = Registry.getInstance();
						registry.updateLogRegistry(_id,date.getText().toString(),weight.getText().toString(),weightKilograms);
						Cursor cursor = DataBaseHelper.getInstance().getCursor(weightKilograms);
						cursorAd.changeCursor(cursor);
						return true;
						}
						return false;
					}
				};
				
				date.setOnKeyListener(keyListener);
				weight.setOnKeyListener(keyListener);
            }
        };
        
        setListAdapter(cursorAd);
        
        registerForContextMenu(send_mail);

        send_mail.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				openContextMenu(send_mail);
			}
		});

    }
    
    public void onCreateContextMenu( ContextMenu menu, View view, ContextMenuInfo menuInfo ) {
        MenuInflater inflater = getMenuInflater();
        if ( view == send_mail ) {
             inflater.inflate(R.menu.choosemailmenu, menu);
             menu.setHeaderTitle(R.string.choose_mail);
        }
   }
    
    public boolean onContextItemSelected( MenuItem menuItem ) {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        String mail = "";
        switch ( menuItem.getItemId() ) {
        case R.id.choosefromcontacts:
            Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
            startActivityForResult(intent, PICK_CONTACT);
            break;
        case R.id.mymail:
            mail = pref.getString("mail", null);
            break;
        case R.id.recipientmail:
            mail = pref.getString("recipientmail", null);
            break;
        } 
        if(!mail.equals("")) {
            sendMail(cursorAd.getCursor(),mail);
        }
        return true;
     }
    
    
	
	@Override
    protected void onActivityResult( int requestCode, int resultCode, Intent data ) {	    
	    
	    switch (requestCode) {
	    case (PICK_CONTACT) :
	      if (resultCode == Activity.RESULT_OK) {
	        Uri contactData = data.getData();	        
	        if(contactData!=null) {
	            Cursor c =  managedQuery(contactData, null, null, null, null);
    	        if (c.moveToFirst()) {
    	          String emailid = c.getString(c.getColumnIndexOrThrow(People.PRIMARY_EMAIL_ID));
    	          String email = null;
    	          if (emailid != null) {  
    	                Cursor emailCur = getContentResolver().query(  
    	                        Contacts.ContactMethods.CONTENT_EMAIL_URI, null,  
    	                        People.PRIMARY_EMAIL_ID + " = ?",  
    	                        new String[] { emailid }, null);  
    	                while (emailCur.moveToNext()) {  
    	                    email = emailCur.getString(emailCur  
    	                            .getColumnIndex(Contacts.ContactMethods.DATA));  
    	                    break;  
    	                }  
    	                emailCur.close();  
    	                emailCur = null;  
    	            } 
    	          
    	          
    	          
    	          if(email!=null) {
    	              sendMail(cursorAd.getCursor(),email);
    	          }
    	        }
	        } else {
	           Bundle bundle = data.getExtras();
	           android.util.Log.d("[BUNDLE]","Bundle.Size()" +  bundle.size());
	        }
	      }
	      break;
	  }
    }

    private void sendMail(Cursor cursor,String recipientName){
	          String report = Registry.getInstance().createHTMLReport(cursor);
	          File file = Utilities.createFileFromReport(report);
		      final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		      SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
		      Uri uri = Uri.parse(file.getAbsolutePath());
		      String name = pref.getString("name", null);
		      String contact = recipientName;
		      if(contact!=null && name!=null) {
    		      emailIntent .setType("plain/html");
    		      emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{contact});
    		      emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.mail_subject)+ " " + name);
    		      emailIntent .putExtra(android.content.Intent.EXTRA_STREAM, Uri.fromFile(file));
    		      emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(report));
    		      this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
		      }
	}
    
    
    
}
